var listPage = avalon.define({
    $id: "listtestPage",
    layout: true,
    cid: '',
    noProductData: "",
    categoryId: "",
    subCategoryId: "",
    checked: {},
    // isChecked: function(value) {
    //     var checked = listPage.checked;
    //     if (null != checked[value]) {
    //         return true;
    //     } else {
    //         return false;
    //     }
    // },
    data: {
        childs: [],
        isSmall: 0,
        categorys: [],
        subcategorys: [],
        parent: {
            name: ""
        },
        facets: []
    },
    pages: 2,
    fact: [],
    getFacets: function(cid, type) {
        mui.ajax('/product/facet.json', {
            data: { cid: 506, type: type },
            dataType: 'json',
            type: "post",
            success: function(data) {
                listPage.data.facets = data.facets;
                //1:获取筛选项 0：根据下拉框获取筛选项
                if (1 == type) {
                    listPage.data.parent = data.parent;
                    listPage.data.isSmall = data.parent.isSmall;

                    if (1 == listPage.data.isSmall) {
                        listPage.data.categorys = data.childs;
                        //选中下拉框
                        listPage.subCategoryId = window.localStorage.getItem('dahua_sid');
                        listPage.chooseCategory();
                    }

                    //控制filter的显示
                    if (data.facets.length > 0 || 1 == listPage.data.isSmall) {
                        if (!$(".filterBtn").hasClass("filter")) {
                            $(".filterBtn").addClass("filter")
                        }
                    } else {
                        $(".filter-bar").addClass("mui-hidden");
                        $("#productList").removeClass("mt91");
                        $(".mui-pull-top-pocket").css("top", "44px");
                    }
                }

            }
        });
    },
    //一类变化
    chooseCategory: (to) => {
        var categoryId = listPage.categoryId;
        sessionStorage.setItem('subCategoryId', to.target.value);
        if (categoryId) {
            setTimeout(() => {
                listPage.getsubcategory();
                $("#subcategory option:first").prop("selected", 'selected');
            }, 10)
        }
        $('input:checkbox').removeAttr('checked');
    },
    //二类变化
    chooseSubCategory: (to) => {
        var subCategoryId = listPage.subCategoryId;
        listPage.cid = to.target.value;
        sessionStorage.setItem('subCategoryId', listPage.cid)
        if (subCategoryId) {
            mui.ajax('/product/search.json', {
                data: {
                    'cid': listPage.cid,
                    'facetIds': [],
                    'page': 1,
                    'pageSize': 15
                },
                dataType: 'json',
                success: (data) => {
                    // listPage.data.childs = data.products;
                    if (data.success == false) {
                        listPage.noProductData = "<img src='../../resources/images/noDataImg.png'><p>No data</p>";
                        $(".compareBtn").addClass("mui-hidden");
                    } else {
                        $(".compareBtn").removeClass("mui-hidden");
                    }
                    listPage.getattr();
                }
            })
        }
        $('input:checkbox').removeAttr('checked');
    },
    //重置搜索条件
    // resetFacetFields: function() {
    //     window.localStorage.setItem('dahua_facets', "");
    //     listPage.checked = {};
    //     window.localStorage.setItem('dahua_sid', "");

    //     if (1 == listPage.data.isSmall) {
    //         listPage.data.facets = [];
    //         listPage.subCategoryId = "";
    //     }
    // },
    //保存搜索条件
    saveFacetFields: function(facets) {
        window.localStorage.setItem('dahua_facets', JSON.stringify(facets));
    },
    //保存搜索条件
    saveFacetSid: function(sid) {
        window.localStorage.setItem('dahua_sid', sid);
    },
    //保存搜索条件
    saveFacetCid: function(cid) {
        window.localStorage.setItem('dahua_cid', cid);
    },
    //获取搜索条件
    getFacetFields: function() {
        var data = window.localStorage.getItem("dahua_facets");
        if ("" == data || null == data) {
            return {};
        } else {
            return JSON.parse(data);
        }
    },
    compare: {
        btnText: '',//"Product Comparison",
        values: [],
        max: 9,
        selected: function(id) {
            var icheckbox = $('#' + id);
            if ($(".compareBtn").hasClass("compared")) {
                var max = this.max;
                var values = this.values;
                if (icheckbox.is(':checked')) {
                    if (values.length + 1 > max) {
                        $(icheckbox).attr("checked", false);
                        mui.toast("You can choose " + max + " products at most");
                    } else {
                        values.push(id);
                        // this.btnText = "Complete(" + values.length + "/" + max + ")";
                        this.btnText = $.i18n.prop('Complete')+"(" + values.length + "/" + max + ")";
                        this.values = values;
                    }
                } else {
                    var tmpValues = [];
                    avalon.each(values, function(i, value) {
                        if (id != value) {
                            tmpValues.push(value);
                        }
                    });
                    this.values = tmpValues;
                    // this.btnText = "Complete(" + tmpValues.length + "/" + max + ")";
                    this.btnText = $.i18n.prop('Complete')+"(" + tmpValues.length + "/" + max + ")";
                }
            } else {
                $(icheckbox).attr("checked", false);
                var url = "pdp.html?id=" + id;
                mui.openWindow({
                    url: url
                });
            }

        }
    },
    getcategory() {
        mui.ajax('/category/getSearchCategory.json', {
            dataType: 'json',
            success: (data) => {
                listPage.data.categorys = data;
                sessionStorage.setItem('subCategoryId', data[0].id);
                // setTimeout(() => { listPage.getsubcategory() }, 10);
                // var todo = $.getParameter('todo');
                var todo = sessionStorage.getItem('todo')
                if (todo == 2) {
                    // $('.mui-inner-wrap').addClass('pp')
                    var btn = document.getElementById("pop");
                    //监听点击事件
                    btn.addEventListener("tap", function() {
                        mui('.mui-off-canvas-wrap').offCanvas('show');
                    });
                    //触发submit按钮的点击事件
                    mui.trigger(btn, 'tap');
                }
            }
        })
    },
    getsubcategory() {
        mui.ajax('/category/getSubCategory.json', {
            dataType: 'json',
            data: { 'categoryId': sessionStorage.getItem('subCategoryId') },
            success: (data) => {
                listPage.data.subcategorys = data;
                //控制filter的显示
                if (listPage.data.subcategorys.length > 0) {
                    if (!$(".filterBtn").hasClass("filter")) {
                        $(".filterBtn").addClass("filter")
                    }
                } else {
                    $(".filter-bar").addClass("mui-hidden");
                    $("#productList").removeClass("mt91");
                    $(".mui-pull-top-pocket").css("top", "44px");
                }
                listPage.cid = data[0].id;
                // listPage.getattr();
            }
        })
    },
    //获取搜索属性
    getattr() {
        mui.ajax('/category/getSearchByCategory.json', {
            dataType: 'json',
            data: { 'categoryId': listPage.cid },
            success: (data) => {
                listPage.data.facets = data;
            }
        })
    },
    //获取产品列表
    getlist() {
        mui.ajax('/product/search.json', {
            data: {
                'cid': listPage.cid,
                'facetIds': sessionStorage.getItem('fact'),
                'page': 1,
                'pageSize': 15
            },
            dataType: 'json',
            success: (data) => {
                listPage.data.childs = data.products;
                if (data.success == false) {
                    listPage.noProductData = "<img src='../../resources/images/noDataImg.png'><p>No data</p>";
                    $(".compareBtn").addClass("mui-hidden");
                } else {
                    $(".compareBtn").removeClass("mui-hidden");
                }
            }
        })
    },
    //获取产品列表
    getMlist() {
        mui.ajax('/category/getSearchCategory.json', {
            dataType: 'json',
            success: (data) => {
                listPage.data.categorys = data;
                sessionStorage.setItem('cidA', data[0].id);
                setTimeout(() => {
                    mui.ajax('/category/getSubCategory.json', {
                        dataType: 'json',
                        data: { 'categoryId': sessionStorage.getItem('cidA') },
                        success: (data) => {
                            listPage.data.subcategorys = data;
                        }
                    })
                })
            }
        })
    }
});


mui.ready(function() {
	listPage.compare.btnText=$.i18n.prop('Product_Comparison');
    var filterCanvasWrapper = mui('#filterCanvasWrapper');
    mui(".filter-bar").on('tap', '.filter', function() {
        filterCanvasWrapper.offCanvas('show');
    });
    //获取产品列表
    listPage.getMlist();
    // listPage.getsubcategory();
    if (sessionStorage.getItem('todo') == 1) {
        // mui('#productList').pullRefresh().disablePullupToRefresh(); //禁止上拉加载
        //filter事件
        var btn = document.getElementById("pop");
        btn.addEventListener("tap", function() {
            mui('.mui-off-canvas-wrap').offCanvas('show');
        });
        mui.init({
            gestureConfig: {
                tap: true, //默认为true 
                doubletap: true, //默认为false 
                longtap: true
            },
            pullRefresh: {
                container: "#productList",
                down: {
                    auto: true,
                    contentdown: $.i18n.contentDown,
                    contentover: $.i18n.contentOver,
                    contentrefresh: $.i18n.contentRefresh,
                    callback: function() {
                        listPage.noProductData = "";
                        setTimeout(function() {
                            mui.ajax('/product/search.json', {
                                data: {
                                    'cid': sessionStorage.getItem('subCategoryId'),
                                    'facetIds': JSON.parse(sessionStorage.getItem('fact')),
                                    'page': 1,
                                    'pageSize': 15
                                },
                                dataType: 'json',
                                success: function(data) {
                                    listPage.data.childs = data.products;
                                    listPage.pages = 2;
                                    if (!data.products) {
                                        listPage.noProductData = "<img src='../../resources/images/noDataImg.png'><p>No data</p>";
                                        $(".compareBtn").addClass("mui-hidden");
                                    } else {
                                        $(".compareBtn").removeClass("mui-hidden");
                                    }
                                    if (!$(".filterBtn").hasClass("filter")) {
                                        $(".filterBtn").addClass("filter")
                                    }
                                    mui('#productList').pullRefresh().endPulldownToRefresh();
                                }
                            });
                        }, window.DAHUA_CONFIG.LOADING_TIME);
                    }
                },
                up: {
                    auto: true, //可选,默认false.自动上拉加载一次
                    contentnomore: $.i18n.noData, //可选，请求完毕若没有更多数据时显示的提醒内容；
                    callback: function() { //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
                        setTimeout(() => {
                            listPage.noProductData = "";
                            var pageSize = 15; //每页显示的数据
                            var isOver = false; //是否加载完
                            mui.ajax('/product/search.json', {
                                timeout: 3000,
                                data: {
                                    'page': listPage.pages,
                                    'pageSize': pageSize,
                                    'cid': sessionStorage.getItem('subCategoryId'),
                                    'facetIds': JSON.parse(sessionStorage.getItem('fact'))
                                },
                                dataType: "json",
                                success: function(data) {
                                    mui.each(data.products, (i, item) => {
                                        listPage.data.childs.push(item);
                                    })
                                    if (data.success == true) {
                                        //判断是否还有数据,若小于每次加载条数,结束
                                        if (data.products.length > pageSize) {
                                            isOver = true;
                                        }
                                        //每次加载结束之后，如果还有数据则++
                                        if (isOver == false) {
                                            listPage.pages++;
                                        }
                                        if (data.products.length == 0) {
                                            mui.toast($.i18n.noData);
                                        }
                                    }
                                    mui('#productList').pullRefresh().endPullupToRefresh((isOver)); //参数为true代表没有更多数据了。
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    console.log("请求失败!!！" + textStatus);
                                }
                            });
                        }, window.DAHUA_CONFIG.LOADING_TIME)
                    }
                }
            }
        });
    } else {
        listPage.getcategory();
        mui.init({
            gestureConfig: {
                tap: true, //默认为true 
                doubletap: true, //默认为false 
                longtap: true
            },
            pullRefresh: {
                container: "#productList",
                down: {
                    auto: true,
                    contentdown: $.i18n.contentDown,
                    contentover: $.i18n.contentOver,
                    contentrefresh: $.i18n.contentRefresh,
                    callback: function() {
                        listPage.noProductData = "";
                        setTimeout(function() {
                            mui.ajax('/product/search.json', {
                                data: {
                                    'cid': sessionStorage.getItem('subCategoryId'),
                                    'facetIds': sessionStorage.getItem('fact'),
                                    'page': 1,
                                    'pageSize': 15
                                },
                                dataType: 'json',
                                success: function(data) {
                                    listPage.data.childs = data.products;
                                    listPage.pages = 2;
                                    if (data.products.length == 0) {
                                        listPage.noProductData = "<img src='../../resources/images/noDataImg.png'><p>No data</p>";
                                        $(".compareBtn").addClass("mui-hidden");
                                    } else {
                                        $(".compareBtn").removeClass("mui-hidden");
                                    }
                                    mui('#productList').pullRefresh().endPulldownToRefresh();
                                }
                            });
                        }, window.DAHUA_CONFIG.LOADING_TIME);
                    }
                },
                up: {
                    auto: true, //可选,默认false.自动上拉加载一次
                    contentnomore: $.i18n.noData, //可选，请求完毕若没有更多数据时显示的提醒内容；
                    callback: function() { //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
                        setTimeout(() => {
                            listPage.noProductData = "";
                            var pageSize = 15; //每页显示的数据
                            var isOver = false; //是否加载完
                            mui.ajax('/product/search.json', {
                                timeout: 3000,
                                data: {
                                    'page': listPage.pages,
                                    'pageSize': pageSize,
                                    'cid': sessionStorage.getItem('subCategoryId'),
                                    'facetIds': [sessionStorage.getItem('fact')]
                                },
                                dataType: "json",
                                success: function(data) {
                                    mui.each(data.products, (i, item) => {
                                        listPage.data.childs.push(item);
                                    })
                                    if (data.success == true) {
                                        //判断是否还有数据,若小于每次加载条数,结束
                                        if (data.products.length > pageSize) {
                                            isOver = true;
                                        }
                                        //每次加载结束之后，如果还有数据则++
                                        if (isOver == false) {
                                            listPage.pages++;
                                        }
                                        if (data.products.length == 0) {
                                            mui.toast($.i18n.noData);
                                        }
                                    }
                                    mui('#productList').pullRefresh().endPullupToRefresh((isOver)); //参数为true代表没有更多数据了。
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    console.log("请求失败!!！" + textStatus);
                                }
                            });
                        }, window.DAHUA_CONFIG.LOADING_TIME)
                    }
                }
            }
        });
    }

    //layout布局
    mui(".mui-bar-nav").on('tap', '.layout', function() {
        var layout = listPage.layout;
        if (layout) {
            listPage.layout = false;
        } else {
            listPage.layout = true;
        }
    });

    //reset按钮
    mui(".filter-btn").on('tap', '.resetBtn', function() {
        // document.getElementById('facetForm').reset();
        // mui.ajax('/category/getSearchCategory.json', {
        //     dataType: 'json',
        //     success: (data) => {
        //         listPage.data.categorys = data;
        //         sessionStorage.setItem('AA', data[0].id)
        //     }
        // });
        // mui.ajax('/category/getSubCategory.json', {
        //     dataType: 'json',
        //     data: { 'categoryId': sessionStorage.getItem('AA') },
        //     success: (data) => {
        //         listPage.data.subcategorys = data;
        //         // sessionStorage.setItem('BB', data[0].id)
        //         mui.ajax('/category/getSearchByCategory.json', {
        //             dataType: 'json',
        //             data: { 'categoryId': data[0].id },
        //             success: (data) => {
        //                 listPage.data.facets = data;
        //             }
        //         })
        //     }
        // })
        $("input[name='facetbox']:checked").each(function(i, e) { //把所有被选中的复选框的值存入数组
            $(this).removeAttr("checked")
        });

    });
    //搜索按钮
    mui(".filter-btn").on('tap', '.searchBtn', function() {
        listPage.noProductData = "";
        var fact = [];
        $("input[name='facetbox']:checked").each(function(i, e) { //把所有被选中的复选框的值存入数组
            fact.push($(this).val())
        });
        sessionStorage.setItem('fact', [])
        mui.ajax('/product/search.json', {
            data: { 'cid': sessionStorage.getItem('subCategoryId'), "facetIds": fact, "page": 1, "pageSize": 15 },
            dataType: 'json',
            success: function(data) {
                mui('.mui-off-canvas-wrap').offCanvas('show');
                listPage.data.childs = data.products;
                if (!data.products) {
                    listPage.noProductData = "<img src='../../resources/images/noDataImg.png'><p>No data</p>";
                    $(".compareBtn").addClass("mui-hidden");
                } else {
                    mui('#productList').scroll().scrollTo(0, 0, 100);
                    $(".compareBtn").removeClass("mui-hidden");
                }

                //保存查询条件
                sessionStorage.setItem('fact', [JSON.stringify(fact)]);
            }
        });
        // mui('#productList').pullRefresh().enablePullupToRefresh();
    });

    //search按钮
    mui(".mui-bar-nav").on('tap', '.search', function() {
        var url = this.getAttribute('href');
        mui.openWindow({
            url: url
        });
    });

    //点击开始比较按钮
    mui(".filter-bar").on('tap', '.startCompare', function() {
        listPage.compare.btnText = $.i18n.prop('Complete');//"Complete";
        //隐藏不需要比较的类目
        if (1 == listPage.data.isSmall) {
            $(".catItems").addClass("mui-hidden");
            avalon.each(listPage.data.categorys, function(i, category) {
                $("#" + category.id).removeClass("mui-hidden");
            });
        }
        if ($(".icheckbox").hasClass("mui-hidden")) {
            $(".icheckbox").removeClass("mui-hidden");
        }
        if (!$(".product").hasClass("mui-checkbox")) {
            $(".product").addClass("mui-checkbox");
        }

        if (!$(".compareBtn").hasClass("compared")) {
            $(".compareBtn").addClass("compared");
        }
        if ($(".compareBtn").hasClass("startCompare")) {
            $(".compareBtn").removeClass("startCompare");
        }
        $("#pop").addClass("pops"); //禁止点击filter
        mui('#productList').pullRefresh().disablePullupToRefresh(); //禁止上拉加载
    });

    //跳转到比较页面
    mui(".filter-bar").on('tap', '.compared', function() {
        $("#pop").removeClass("pops"); //释放filter
        mui('#productList').pullRefresh().enablePullupToRefresh(); //启用上拉加载
        var values = listPage.compare.values;
        if (values.length == 0) {
            listPage.compare.btnText = $.i18n.prop('Product_Comparison');//"Product Comparison";
            $(".pro").addClass("mui-hidden");
            $(".compareBtn").addClass("startCompare");
            $(".compareBtn").removeClass("compared");
            if (1 == listPage.data.isSmall) {
                $(".catItems").removeClass("mui-hidden");
            }

        } else if (values.length == 1) {
            mui.toast('Select two products at least');
        } else {
            var url = "compare.html";
            mui.openWindow({
                url: url + "?id=" + values
            });
        }
    });


    //获取更多商品
    mui("#productList").on('tap', '.getMore', function() {
        var id = this.getAttribute('data-id');
        var facetForm = $("#facetForm").serialize();
        mui.ajax("/product/more.json?id=" + id, {
            data: facetForm,
            dataType: 'json',
            type: "post",
            success: function(data) {
                for (var i = 0; i < listPage.data.childs.length; i++) {
                    if (id == listPage.data.childs[i].id) {
                        var products = listPage.data.childs[i].products;
                        products.push.apply(products, data.products);
                        listPage.data.childs[i].products = products;
                    }
                }
                $("#cat" + id).hide();

                if ($(".compareBtn").hasClass("compared")) {
                    $(".icheckbox").removeClass("mui-hidden");
                    $(".product").addClass("mui-checkbox");
                }
            }
        });
    });

});